package org.zhq.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.zhq.Const;
import org.zhq.enums.Sex;
import org.zhq.mapper.UsersMapper;
import org.zhq.pojo.Users;
import org.zhq.pojo.bo.UserBO;
import org.zhq.pojo.vo.UsersVO;
import org.zhq.service.UsersService;
import org.zhq.utils.CookieUtils;
import org.zhq.utils.MD5Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.UUID;

@Service
public class UsersServiceImpl implements UsersService {

    public static final String USER_FACE = "http://b-ssl.duitang.com/uploads/item/201802/21/20180221223815_xkkyq.jpg";

    private final UsersMapper usersMapper;
    private final StringRedisTemplate redisTemplate;

    @Autowired
    public UsersServiceImpl(UsersMapper usersMapper, StringRedisTemplate redisTemplate) {
        this.usersMapper = usersMapper;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 判断用户名是否存在
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String username) {
        Integer count = usersMapper.selectCount(Wrappers.<Users>lambdaQuery().eq(Users::getUsername, username));
        return count > 0;
    }

    /**
     * 创建用户
     *
     * @param userBO
     * @return
     */
    @Transactional
    @Override
    public Users createUser(UserBO userBO) {
        Users users = new Users();
        users.setUsername(userBO.getUsername());
        //0.MD5加密
        users.setPassword(MD5Utils.getMD5Str(userBO.getPassword()));
        //1.赋值昵称头像信息生日性别
        users.setNickname(userBO.getUsername());
        users.setFace(Optional.ofNullable(userBO.getFace()).orElse(USER_FACE));
        users.setBirthday(Optional.ofNullable(DateUtil.parse(userBO.getBirthday())).orElse(DateUtil.parse("1900-01-01")));
        users.setSex(Optional.ofNullable(userBO.getSex()).orElse(Sex.SECRET.type));
        users.setCreatedTime(DateUtil.date());
        users.setUpdatedTime(DateUtil.date());
        usersMapper.insert(users);
        return users;
    }

    /**
     * 登录 检索用户名密码是否匹配
     *
     * @param username
     * @param password
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserForLogin(String username, String password) {
        //0.根据username password 查询用户
        LambdaQueryWrapper<Users> condition = Wrappers.<Users>lambdaQuery().eq(Users::getUsername, username).eq(Users::getPassword, password);
        return usersMapper.selectOne(condition);
    }

    @Override
    public void storeUserForLogin(UsersVO users, HttpServletRequest request, HttpServletResponse response) {
        String token = UUID.randomUUID().toString();
        users.setUserUniqueToken(token);
        redisTemplate.opsForValue().set(Const.Redis.USER_TOKEN + ":" + users.getId(), token);
        CookieUtils.setCookie(request, response, Const.CURRENT_USER, JSONUtil.toJsonStr(users), true);
    }

    @Override
    public void removeUserForLogin(String userId, HttpServletRequest request, HttpServletResponse response) {
        redisTemplate.delete(Const.Redis.USER_TOKEN + ":" + userId);
        CookieUtils.deleteCookie(request, response, Const.CURRENT_USER);
    }
}
